package com.zhhs.galaxyott.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.zhhs.galaxyott.R;
import com.zhhs.galaxyott.adapters.ListFragmentAdapter;
import com.zhhs.galaxyott.adapters.MoviesPagersAdapter;
import com.zhhs.galaxyott.beans.CategoryBean;
import com.zhhs.galaxyott.beans.HomeMovieBean;
import com.zhhs.galaxyott.customview.DirectionalViewPager;
import com.zhhs.galaxyott.customview.myListView;
import com.zhhs.galaxyott.http.api.RequestMaker;
import com.zhhs.galaxyott.httpVolley.base.ResponseListener;
import com.zhhs.galaxyott.httpVolley.response.CategoryListResponse;
import com.zhhs.galaxyott.httpVolley.response.HomemovieListResponse;
import com.zhhs.galaxyott.utils.Logs;

/**
 * 
 * @author lc
 * @created 2016年6月29日 注：此Activity已被替代
 */
public class MoreMoviesActivity extends FragmentActivity implements OnClickListener {

    private static String TAG = MoreMoviesActivity.class.getSimpleName();

    public static myListView mListView;
    public static LinearLayout mtitleLayout;
    private ListFragmentAdapter mlistAdapter;
    private static int pos;

    private static int index = 0;
    private List<CategoryBean> titleData;
    private List<HomeMovieBean> specialData;

    public static ImageView imageLeft, imageRight;
    private ImageView type_img;

    public static boolean detailFocus = false;
    public boolean isFirstLoad = true;
    public static boolean isViewPager = false;

    private List<View> mViews;
    protected MoviesPagersAdapter mVpAdapter;

    private DirectionalViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pos = getIntent().getIntExtra("type", 0);

        isFirstLoad = true;
        isList = true;
        detailFocus = false;
        listpos = pos;

        setContentView(R.layout.activity_more_movies);

        type_img = (ImageView) findViewById(R.id.type_img);
        type_img.setBackgroundResource(R.drawable.movielist_img);

        imageLeft = (ImageView) findViewById(R.id.iv_activity_left);
        imageRight = (ImageView) findViewById(R.id.iv_activity_right);
        imageLeft.setOnClickListener(this);
        imageRight.setOnClickListener(this);

        mListView = (myListView) findViewById(R.id.title_layout);
        mViewPager = (DirectionalViewPager) findViewById(R.id.DirectionalViewPager);
        mViewPager.setOrientation(DirectionalViewPager.VERTICAL);

        loadSpecailData();

        // mListView.clearFocus();

        loadData();
    }

    private void loadSpecailData() {
        int page = 2;
        RequestMaker.getHomeMovieList(this, page, new ResponseListener<HomemovieListResponse>() {
            @Override
            public void onResponse(HomemovieListResponse result) {

                if (result == null) {
                    return;
                }

                Logs.logD("DEBUG_DT",
                        "this is loadSpecailData-->" + +result.errCode + "size" + result.homeMovieBeans.size());
                if (result.errCode == 0) {
                    specialData = new ArrayList<HomeMovieBean>();
                    specialData = result.homeMovieBeans;

                    if (result.homeMovieBeans.size() >= 2) {

                        Glide.with(MoreMoviesActivity.this).load(result.homeMovieBeans.get(0).getImageUrl())
                                .crossFade().into(imageLeft);
                        Glide.with(MoreMoviesActivity.this).load(result.homeMovieBeans.get(1).getImageUrl())
                                .crossFade().into(imageRight);
                    }
                }

            }

            @Override
            public void onError(VolleyError error) {
                Logs.logD("DEBUG_DT", "this is loadSpecailData-->err");

            }
        });

    }

    private void loadData() {

        RequestMaker.getCategoryList(this, new ResponseListener<CategoryListResponse>() {

            @Override
            public void onResponse(CategoryListResponse result) {

                Logs.logD("DEBUG_DT", "this is getCategoryList-->" + +result.errCode + "size" + result.Beans.size()
                        + "pos:" + pos);
                if (result.errCode == 0) {

                    titleData = new ArrayList<CategoryBean>();
                    titleData = result.Beans;

                    mListView.setSelection(pos);

                    selectId = pos;

                    mListView.setItemsCanFocus(true);
                    mlistAdapter = new ListFragmentAdapter(MoreMoviesActivity.this, titleData, pos);
                    mListView.setAdapter(mlistAdapter);
                    mListView.setOnItemSelectedListener(mOnItemSelectedListener);

                    mViews = new ArrayList<View>();
                    mViews.removeAll(mViews);
                    for (int i = 0; i < titleData.size(); i++) {
                        mViews.add(getLayoutInflater().inflate(R.layout.fragment_more_movies, null));
                        // mViews.add(getLayoutInflater().inflate(R.layout.movies_grid,
                        // null));

                    }
                    // mVpAdapter = new
                    // MoviesPagersAdapter(MoreMoviesActivity.this, mViews,
                    // titleData);
                    mVpAdapter = new MoviesPagersAdapter(MoreMoviesActivity.this, mViews, titleData);
                    // mViewPager.setOrientation(DirectionalViewPager.VERTICAL);
                    // mViewPager.setOffscreenPageLimit(3);

                    mViewPager.setCurrentItem(pos);
                    mViewPager.setAdapter(mVpAdapter);

                }
            }

            @Override
            public void onError(VolleyError error) {
                Logs.logD("DEBUG_DT", "this is getCategoryList-->err");
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public static int selectId = 0;
    OnItemSelectedListener mOnItemSelectedListener = new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View v, int position, long arg3) {

            Logs.logD("DEBUG_DT", "THIS IS onItemSelected-->" + position);

            if (isFirstLoad) {
                Logs.logD("DEBUG_DT", "THIS IS isFirstLoad-->true");

                isFirstLoad = false;
                selectId = pos;
                mVpAdapter.initViews(pos);

                // mViewPager.setCurrentItem(pos);

                ((TextView) ((FrameLayout) mListView.getChildAt(pos)).getChildAt(0))
                        .setBackgroundResource(R.drawable.title_focus);

            } else {
                Logs.logD("DEBUG_DT", "THIS IS isFirstLoad-->false");
                selectId = position;

                mVpAdapter.initViews(position);
                mViewPager.setCurrentItem(mListView.getSelectedItemPosition());

            }

            mListView.setSelection(selectId);
            mListView.getChildAt(selectId).requestFocus();

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {

        case KeyEvent.KEYCODE_DPAD_DOWN:

            if (((FrameLayout) mListView.getChildAt(titleData.size() - 1)).getChildAt(0).hasFocus()) {
                return true;
            }
            if (imageLeft.hasFocus() || imageRight.hasFocus()) {
                Logs.logD("DEBUG_K", "THIS IS onkeydown--imageRight.hasFocus()");
                return switchFragmentKeyDown(index, keyCode, event);
            }

            break;

        case KeyEvent.KEYCODE_DPAD_UP:

            break;
        case KeyEvent.KEYCODE_DPAD_LEFT:
            if (imageLeft.hasFocus()) {
                detailFocus = false;

            } else if (imageRight.hasFocus()) {
                return super.onKeyDown(keyCode, event);
            }
            break;

        case KeyEvent.KEYCODE_DPAD_RIGHT:

            Logs.logD("DEBUG_K", "THIS IS onkeydown--KEYCODE_DPAD_RIGHT0");
            if (imageLeft.hasFocus() || imageRight.hasFocus()) {
                return super.onKeyDown(keyCode, event);
            }

            break;
        default:

            break;
        }
        Logs.logD("DEBUG_1", "THIS IS onKeyDown--test>0");

        index = selectId;
        // 防止右键移动2个位置
        if (switchFragmentKeyDown(index, keyCode, event))
            return true;
        Logs.logD("DEBUG_1", "THIS IS onKeyDown--test>2");

        if (!detailFocus) {
            isList = true;
            ((TextView) ((FrameLayout) mListView.getChildAt(mListView.getSelectedItemPosition())).getChildAt(0))
                    .setBackgroundResource(R.drawable.titlelist_selector);
            mListView.requestFocus();
        }

        return super.onKeyDown(keyCode, event);
    }

    private static int listpos = 1;
    private static boolean isList = true;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == KeyEvent.ACTION_DOWN) {

            if (titleData.size() == 0) {
                return true;
            }

            switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_DPAD_DOWN:
                if (isList) {
                    if (listpos < titleData.size() - 1) {
                        mListView.setSelection(listpos + 1);
                        ((TextView) ((FrameLayout) mListView.getChildAt(listpos)).getChildAt(0))
                                .setBackgroundResource(R.drawable.rect_transparent_bg);
                        ((TextView) ((FrameLayout) mListView.getChildAt(listpos + 1)).getChildAt(0))
                                .setBackgroundResource(R.drawable.title_focus);
                        mViewPager.setCurrentItem(listpos + 1);
                        listpos = listpos + 1;
                        return true;
                    } else {
                        return true;
                    }

                }

                if (((FrameLayout) mListView.getChildAt(titleData.size() - 1)).getChildAt(0).hasFocus()) {
                    return true;
                }
                if (detailFocus == true && !(imageLeft.hasFocus() || imageRight.hasFocus())) {
                    switchFragmentKeyDown(index, event.getKeyCode(), event);
                }
                break;
            case KeyEvent.KEYCODE_DPAD_UP:
                Logs.logD("DEBUG_1", "THIS IS dispatchKeyEvent--test>");
                if (isList) {
                    if (listpos > 0) {
                        mListView.setSelection(listpos - 1);
                        ((TextView) ((FrameLayout) mListView.getChildAt(listpos)).getChildAt(0))
                                .setBackgroundResource(R.drawable.rect_transparent_bg);
                        ((TextView) ((FrameLayout) mListView.getChildAt(listpos - 1)).getChildAt(0))
                                .setBackgroundResource(R.drawable.title_focus);
                        mViewPager.setCurrentItem(listpos - 1);
                        listpos = listpos - 1;
                        return true;
                    }

                }

                if (detailFocus == true) {
                    switchFragmentKeyDown(index, event.getKeyCode(), event);
                }
                break;

            case KeyEvent.KEYCODE_DPAD_RIGHT:
                Logs.logD("DEBUG_K", "THIS IS dispatchKeyEvent--KEYCODE_DPAD_RIGHT0" + isList);
                if (isList && MoviesPagersAdapter.curpageItem > 0) {
                    isList = false;
                    Logs.logD("DEBUG_K", "THIS IS dispatchKeyEvent--KEYCODE_DPAD_RIGHT");

                    ((TextView) ((FrameLayout) mListView.getChildAt(mListView.getSelectedItemPosition())).getChildAt(0))
                            .setBackgroundResource(R.drawable.title_normal);
                    return switchFragmentKeyDown(listpos, event.getKeyCode(), event);
                }

                if (imageLeft.hasFocus() || imageRight.hasFocus()) {
                    return super.dispatchKeyEvent(event);
                }

                break;

            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (imageLeft.hasFocus()) {
                    detailFocus = false;

                } else if (imageRight.hasFocus()) {
                    return super.dispatchKeyEvent(event);
                }

            default:

                break;

            }

        }

        return super.dispatchKeyEvent(event);
    }

    private Boolean switchFragmentKeyDown(int index, int keyCode, KeyEvent event) {

        return MoviesPagersAdapter.onKeyDown(index, keyCode, event);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
        case R.id.iv_activity_left:
            if (specialData.size() >= 0) {
                startActivity(specialData.get(0));
            }

            break;
        case R.id.iv_activity_right:
            if (specialData.size() >= 1) {
                startActivity(specialData.get(1));
            }

            break;

        default:
            break;
        }
    }

    public void startActivity(HomeMovieBean homeMovieBean) {
        Intent intent = new Intent();
        int type = homeMovieBean.getAdType();
        if (type == 1) {
            intent.setClass(MoreMoviesActivity.this, MovieDetailActivity.class);
            intent.putExtra("movieid", homeMovieBean.getObjectid());
            this.startActivity(intent);

        } else if (type == 2) {
            // intent.setClass(MoreMoviesActivity.this, HotMovieActivity.class);
            // this.startActivity(intent);

        } else if (type == 3) {
            intent.setClass(MoreMoviesActivity.this, MoreSpecialActivity.class);

            this.startActivity(intent);

        } else if (type == 4) {
            intent.setClass(MoreMoviesActivity.this, SingleSpecialActivity.class);
            intent.putExtra("specailId", homeMovieBean.getObjectid());
            this.startActivity(intent);

        } else if (type == 5) {
            intent.setClass(MoreMoviesActivity.this, HotMovieActivity.class);
            intent.putExtra("specailId", homeMovieBean.getObjectid());
            this.startActivity(intent);

        }
    }

}
